<!-- src/ProductManagement.vue -->
<template>
  <div class="admin-management">
    <!-- 顶部标题区域 -->
    <div class="page-header">
      <h2><el-icon><Grid /></el-icon> 后台管理系统</h2>
      <p>管理商品、订单和用户和售后</p>
    </div>

    <!-- 选项卡切换 -->
    <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
      <!-- 商品管理选项卡 -->
      <el-tab-pane label="商品管理" name="products">
        <!-- 商品搜索区域 -->
        <el-card class="search-card">
          <el-form :model="productSearchForm" inline>
            <el-form-item label="商品名称">
              <el-input v-model="productSearchForm.productName" placeholder="输入商品名称" clearable />
            </el-form-item>
            <el-form-item label="发布用户">
              <el-input v-model="productSearchForm.username" placeholder="输入用户名" clearable />
            </el-form-item>
            <el-form-item label="商品状态">
              <el-select v-model="productSearchForm.status" placeholder="选择状态" clearable>
                <el-option label="审核中" :value="0" />
                <el-option label="上架中" :value="1" />
                <el-option label="已下架" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleProductSearch">搜索</el-button>
              <el-button @click="resetProductSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 商品列表 -->
        <el-card>
          <el-table :data="productList" v-loading="productLoading" stripe>
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column prop="productName" label="商品名称" min-width="200" />
            <el-table-column prop="price" label="价格" width="120">
              <template #default="{ row }">¥{{ row.price.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="80" />
            <el-table-column prop="username" label="发布用户" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getProductStatusType(row.status)">{{ getProductStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发布时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  :type="row.status === 1 ? 'danger' : 'success'"
                  @click="handleToggleProductStatus(row)"
                >
                  {{ getProductActionText(row.status) }}
                </el-button>
                <el-button size="small" type="danger" @click="handleDeleteProduct(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 商品分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="productPagination.current"
              v-model:page-size="productPagination.size"
              :total="productPagination.total"
              @current-change="handleProductPageChange"
              @size-change="handleProductSizeChange"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 订单管理选项卡 -->
      <el-tab-pane label="订单管理" name="orders">
        <!-- 订单搜索区域 -->
        <el-card class="search-card">
          <el-form :model="orderSearchForm" inline>
            <el-form-item label="订单号">
              <el-input v-model="orderSearchForm.orderId" placeholder="输入订单号" clearable />
            </el-form-item>
            <el-form-item label="买家用户名">
              <el-input v-model="orderSearchForm.buyerName" placeholder="输入买家用户名" clearable />
            </el-form-item>
            <el-form-item label="订单状态">
              <el-select v-model="orderSearchForm.orderStatus" placeholder="选择状态" clearable>
                <el-option label="待支付" :value="0" />
                <el-option label="已支付" :value="1" />
                <el-option label="已发货" :value="2" />
                <el-option label="已完成" :value="3" />
                <el-option label="已取消" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleOrderSearch">搜索</el-button>
              <el-button @click="resetOrderSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 订单列表 -->
        <el-card>
          <el-table :data="orderList" v-loading="orderLoading" stripe>
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column prop="orderId" label="订单号" min-width="180" />
            <el-table-column prop="buyerName" label="买家" width="120" />
            <el-table-column prop="sellerId" label="卖家ID" width="100">
              <template #default="{ row }">{{ row.sellerId || '未知' }}</template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="订单金额" width="120">
              <template #default="{ row }">¥{{ row.totalAmount.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column prop="orderStatus" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getOrderStatusType(row.orderStatus)">{{ getOrderStatusText(row.orderStatus) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="handleViewOrderDetail(row)">查看详情</el-button>
                <el-button 
                  size="small" 
                  type="warning" 
                  :disabled="row.orderStatus !== 0 && row.orderStatus !== 1"
                  @click="handleCancelOrder(row)"
                >
                  取消订单
                </el-button>
                <el-button 
                  size="small" 
                  type="success" 
                  :disabled="row.orderStatus !== 2"
                  @click="handleCompleteOrder(row)"
                >
                  完成订单
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 订单分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="orderPagination.current"
              v-model:page-size="orderPagination.size"
              :total="orderPagination.total"
              @current-change="handleOrderPageChange"
              @size-change="handleOrderSizeChange"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 用户管理选项卡 -->
      <el-tab-pane label="用户管理" name="users">
        <!-- 用户搜索区域 -->
        <el-card class="search-card">
          <el-form :model="userSearchForm" inline>
            <el-form-item label="用户名">
              <el-input v-model="userSearchForm.username" placeholder="输入用户名" clearable />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="userSearchForm.phone" placeholder="输入手机号" clearable />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userSearchForm.email" placeholder="输入邮箱" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUserSearch">搜索</el-button>
              <el-button @click="resetUserSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 用户列表 -->
        <el-card>
          <el-table :data="userList" v-loading="userLoading" stripe>
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column prop="id" label="用户ID" width="80" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="phone" label="手机号" width="130" />
            <el-table-column prop="email" label="邮箱" min-width="180" />
            <el-table-column prop="realname" label="真实姓名" width="100" />
            <el-table-column prop="wechat" label="微信号" width="120" />
            <el-table-column prop="sign" label="个性签名" min-width="150" :show-overflow-tooltip="true" />
            <el-table-column prop="money" label="账户余额" width="120">
              <template #default="{ row }">¥{{ row.money.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="handleEditUser(row)">编辑</el-button>
                <el-button size="small" @click="handleViewUserDetail(row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 用户分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="userPagination.current"
              v-model:page-size="userPagination.size"
              :total="userPagination.total"
              @current-change="handleUserPageChange"
              @size-change="handleUserSizeChange"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-tab-pane>
      <!-- 售后管理选项卡 -->
      <el-tab-pane label="售后管理" name="afterSales">
        <!-- 售后搜索区域 -->
        <el-card class="search-card">
          <el-form :model="afterSaleSearchForm" inline>
            <el-form-item label="订单号">
              <el-input v-model="afterSaleSearchForm.orderId" placeholder="输入订单号" clearable />
            </el-form-item>
            <el-form-item label="买家用户名">
              <el-input v-model="afterSaleSearchForm.buyerName" placeholder="输入买家用户名" clearable />
            </el-form-item>
            <el-form-item label="售后类型">
              <el-select v-model="afterSaleSearchForm.type" placeholder="选择类型" clearable>
                <el-option label="退款" :value="1" />
                <el-option label="举报" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="售后状态">
              <el-select v-model="afterSaleSearchForm.status" placeholder="选择状态" clearable>
                <el-option label="申请中" :value="0" />
                <el-option label="卖家协调中" :value="1" />
                <el-option label="平台审核中" :value="2" />
                <el-option label="已通过" :value="3" />
                <el-option label="已拒绝" :value="4" />
                <el-option label="确认完成" :value="5" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAfterSaleSearch">搜索</el-button>
              <el-button @click="resetAfterSaleSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 售后列表 -->
        <el-card>
          <el-table :data="afterSaleList" v-loading="afterSaleLoading" stripe>
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column prop="afterSaleId" label="售后ID" width="80" />
            <el-table-column prop="orderId" label="订单号" min-width="150" />
            <el-table-column prop="buyerName" label="买家" width="120" />
            <el-table-column prop="type" label="类型" width="80">
              <template #default="{ row }">
                <el-tag :type="row.type === 1 ? 'warning' : 'danger'">
                  {{ getAfterSaleTypeText(row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="申请理由" min-width="200" :show-overflow-tooltip="true" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getAfterSaleStatusType(row.status)">
                  {{ getAfterSaleStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="申请时间" width="180" />
            <el-table-column prop="processTime" label="处理时间" width="180">
              <template #default="{ row }">{{ row.processTime || '未处理' }}</template>
            </el-table-column>
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="handleViewAfterSaleDetail(row)">详情</el-button>
                <el-select 
                  v-model="row.status" 
                  size="small" 
                  style="width: 120px; margin: 0 10px;"
                  @change="(value) => handleUpdateAfterSaleStatus(row, value)"
                >
                  <el-option label="申请中" :value="0" />
                  <el-option label="卖家协调中" :value="1" />
                  <el-option label="平台审核中" :value="2" />
                  <el-option label="已通过" :value="3" />
                  <el-option label="已拒绝" :value="4" />
                  <el-option label="确认完成" :value="5" />
                </el-select>
              </template>
            </el-table-column>
          </el-table>

          <!-- 售后分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="afterSalePagination.current"
              v-model:page-size="afterSalePagination.size"
              :total="afterSalePagination.total"
              @current-change="handleAfterSalePageChange"
              @size-change="handleAfterSaleSizeChange"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="orderDetailVisible" title="订单详情" width="600px">
      <el-descriptions v-if="currentOrder" :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="买家">{{ currentOrder.buyerName }}</el-descriptions-item>
        <el-descriptions-item label="卖家ID">{{ currentOrder.sellerId || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(currentOrder.orderStatus)">{{ getOrderStatusText(currentOrder.orderStatus) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ currentOrder.payTime || '未支付' }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ currentOrder.sendTime || '未发货' }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ currentOrder.finishTime || '未完成' }}</el-descriptions-item>
        <el-descriptions-item label="地址ID">{{ currentOrder.addressId }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="userDetailVisible" title="用户详情" width="700px">
      <el-descriptions v-if="currentUser" :column="2" border>
        <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
        <el-descriptions-item label="真实姓名">{{ currentUser.realname || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="微信号">{{ currentUser.wechat || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="个性签名" :span="2">{{ currentUser.sign || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="账户余额">¥{{ currentUser.money.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <div v-if="currentUser.avatar">
            <el-image 
              :src="'http://localhost:8088/dev/uploads/' + currentUser.avatar" 
              style="width: 60px; height: 60px; border-radius: 50%;"
              :preview-src-list="['http://localhost:8088/dev/uploads/' + currentUser.avatar]"
              preview-teleported
            />
          </div>
          <span v-else>未设置</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="userEditVisible" title="编辑用户信息" width="500px">
      <el-form v-if="currentUser" :model="userEditForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userEditForm.username" />
        </el-form-item>
        <el-form-item label="个性签名">
          <el-input v-model="userEditForm.sign" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="头像文件名">
          <el-input v-model="userEditForm.avatar" placeholder="输入头像文件名，如：avatar.jpg" />
        </el-form-item>
        <el-form-item label="账户余额">
          <el-input-number v-model="userEditForm.money" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userEditVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </template>
    </el-dialog>

    <!-- 售后详情对话框 -->
    <el-dialog v-model="afterSaleDetailVisible" title="售后详情" width="600px">
      <el-descriptions v-if="currentAfterSale" :column="2" border>
        <el-descriptions-item label="售后ID">{{ currentAfterSale.afterSaleId }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ currentAfterSale.orderId }}</el-descriptions-item>
        <el-descriptions-item label="买家">{{ currentAfterSale.buyerName }}</el-descriptions-item>
        <el-descriptions-item label="买家ID">{{ currentAfterSale.userId }}</el-descriptions-item>
        <el-descriptions-item label="售后类型">
          <el-tag :type="currentAfterSale.type === 1 ? 'warning' : 'danger'">
            {{ getAfterSaleTypeText(currentAfterSale.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getAfterSaleStatusType(currentAfterSale.status)">
            {{ getAfterSaleStatusText(currentAfterSale.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请理由" :span="2">{{ currentAfterSale.reason }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentAfterSale.createTime }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ currentAfterSale.processTime || '未处理' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 配置axios基础URL - 根据后端配置调整
const API_BASE_URL = 'http://localhost:8088/dev/api/admin'

export default {
  name: 'AdminManagement',
  setup() {
    // 当前激活的选项卡
    const activeTab = ref('products')

    // 商品管理相关状态
    const productLoading = ref(false)
    const productList = ref([])
    const productSearchForm = reactive({
      productName: '',
      username: '',
      status: null
    })
    const productPagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    // 订单管理相关状态
    const orderLoading = ref(false)
    const orderList = ref([])
    const orderSearchForm = reactive({
      orderId: '',
      buyerName: '',
      orderStatus: null
    })
    const orderPagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    // 用户管理相关状态
    const userLoading = ref(false)
    const userList = ref([])
    const userSearchForm = reactive({
      username: '',
      phone: '',
      email: ''
    })
    const userPagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    // 售后管理相关状态
    const afterSaleLoading = ref(false)
    const afterSaleList = ref([])
    const afterSaleSearchForm = reactive({
      orderId: '',
      buyerName: '',
      type: null,
      status: null
    })
    const afterSalePagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    // 订单详情相关状态
    const orderDetailVisible = ref(false)
    const currentOrder = ref(null)

    // 用户详情相关状态
    const userDetailVisible = ref(false)
    const userEditVisible = ref(false)
    const currentUser = ref(null)
    const userEditForm = reactive({
      username: '',
      sign: '',
      avatar: '',
      money: 0
    })

    // 售后详情相关状态
    const afterSaleDetailVisible = ref(false)
    const currentAfterSale = ref(null)

    // 商品状态映射
    const productStatusMap = {
      0: { text: '审核中', type: 'warning', action: '上架', nextStatus: 1 },
      1: { text: '上架中', type: 'success', action: '下架', nextStatus: 2 },
      2: { text: '已下架', type: 'info', action: '上架', nextStatus: 1 }
    }

    // 订单状态映射
    const orderStatusMap = {
      0: { text: '待支付', type: 'warning' },
      1: { text: '已支付', type: 'primary' },
      2: { text: '已发货', type: 'info' },
      3: { text: '已完成', type: 'success' },
      4: { text: '已取消', type: 'danger' }
    }

    // 售后类型映射
    const afterSaleTypeMap = {
      1: { text: '退款', type: 'warning' },
      2: { text: '举报', type: 'danger' }
    }

    // 售后状态映射
    const afterSaleStatusMap = {
      0: { text: '申请中', type: 'info' },
      1: { text: '卖家协调中', type: 'primary' },
      2: { text: '平台审核中', type: 'warning' },
      3: { text: '已通过', type: 'success' },
      4: { text: '已拒绝', type: 'danger' },
      5: { text: '确认完成', type: 'success' }
    }

    // API调用函数 - 商品管理
    const fetchProducts = async () => {
      productLoading.value = true
      try {
        const params = {
          ...productSearchForm,
          page: productPagination.current,
          size: productPagination.size
        }
        const response = await axios.get(`${API_BASE_URL}/products`, { params })
        if (response.data.success) {
          productList.value = response.data.data
          productPagination.total = response.data.total
        } else {
          ElMessage.error('获取商品列表失败')
        }
      } catch (error) {
        console.error('获取商品列表错误:', error)
        ElMessage.error('获取商品列表失败')
      } finally {
        productLoading.value = false
      }
    }

    const updateProductStatus = async (productId, status) => {
      try {
        const response = await axios.put(`${API_BASE_URL}/products/${productId}/status`, { status })
        if (response.data.success) {
          ElMessage.success('状态更新成功')
          fetchProducts() // 重新加载数据
        } else {
          ElMessage.error(response.data.message || '状态更新失败')
        }
      } catch (error) {
        console.error('更新商品状态错误:', error)
        ElMessage.error('状态更新失败')
      }
    }

    const deleteProduct = async (productId) => {
      try {
        const response = await axios.delete(`${API_BASE_URL}/products/${productId}`)
        if (response.data.success) {
          ElMessage.success('删除成功')
          fetchProducts() // 重新加载数据
        } else {
          ElMessage.error(response.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除商品错误:', error)
        ElMessage.error('删除失败')
      }
    }

    // API调用函数 - 订单管理
    const fetchOrders = async () => {
      orderLoading.value = true
      try {
        const params = {
          ...orderSearchForm,
          page: orderPagination.current,
          size: orderPagination.size
        }
        const response = await axios.get(`${API_BASE_URL}/orders`, { params })
        if (response.data.success) {
          orderList.value = response.data.data
          orderPagination.total = response.data.total
        } else {
          ElMessage.error('获取订单列表失败')
        }
      } catch (error) {
        console.error('获取订单列表错误:', error)
        ElMessage.error('获取订单列表失败')
      } finally {
        orderLoading.value = false
      }
    }

    const getOrderDetail = async (orderId) => {
      try {
        const response = await axios.get(`${API_BASE_URL}/orders/${orderId}`)
        if (response.data.success) {
          return response.data.data
        } else {
          ElMessage.error('获取订单详情失败')
          return null
        }
      } catch (error) {
        console.error('获取订单详情错误:', error)
        ElMessage.error('获取订单详情失败')
        return null
      }
    }

    const cancelOrder = async (orderId) => {
      try {
        const response = await axios.put(`${API_BASE_URL}/orders/${orderId}/cancel`)
        if (response.data.success) {
          ElMessage.success('订单取消成功')
          fetchOrders() // 重新加载数据
        } else {
          ElMessage.error(response.data.message || '订单取消失败')
        }
      } catch (error) {
        console.error('取消订单错误:', error)
        ElMessage.error('订单取消失败')
      }
    }

    const completeOrder = async (orderId) => {
      try {
        const response = await axios.put(`${API_BASE_URL}/orders/${orderId}/complete`)
        if (response.data.success) {
          ElMessage.success('订单完成，已自动打款给卖家')
          fetchOrders() // 重新加载数据
        } else {
          ElMessage.error(response.data.message || '订单完成失败')
        }
      } catch (error) {
        console.error('完成订单错误:', error)
        ElMessage.error('订单完成失败')
      }
    }

    // API调用函数 - 用户管理
    const fetchUsers = async () => {
      userLoading.value = true
      try {
        const params = {
          ...userSearchForm,
          page: userPagination.current,
          size: userPagination.size
        }
        const response = await axios.get(`${API_BASE_URL}/users`, { params })
        if (response.data.success) {
          userList.value = response.data.data
          userPagination.total = response.data.total
        } else {
          ElMessage.error('获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表错误:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        userLoading.value = false
      }
    }

    const getUserDetail = async (userId) => {
      try {
        const response = await axios.get(`${API_BASE_URL}/users/${userId}`)
        if (response.data.success) {
          return response.data.data
        } else {
          ElMessage.error('获取用户详情失败')
          return null
        }
      } catch (error) {
        console.error('获取用户详情错误:', error)
        ElMessage.error('获取用户详情失败')
        return null
      }
    }

    const updateUser = async (userId, userData) => {
      try {
        const response = await axios.put(`${API_BASE_URL}/users/${userId}`, userData)
        if (response.data.success) {
          ElMessage.success('用户信息更新成功')
          fetchUsers() // 重新加载数据
          return true
        } else {
          ElMessage.error(response.data.message || '用户信息更新失败')
          return false
        }
      } catch (error) {
        console.error('更新用户信息错误:', error)
        ElMessage.error('用户信息更新失败')
        return false
      }
    }

    // API调用函数 - 售后管理
    const fetchAfterSales = async () => {
      afterSaleLoading.value = true
      try {
        const params = {
          ...afterSaleSearchForm,
          page: afterSalePagination.current,
          size: afterSalePagination.size
        }
        const response = await axios.get(`${API_BASE_URL}/after-sales`, { params })
        if (response.data.success) {
          afterSaleList.value = response.data.data
          afterSalePagination.total = response.data.total
        } else {
          ElMessage.error('获取售后列表失败')
        }
      } catch (error) {
        console.error('获取售后列表错误:', error)
        ElMessage.error('获取售后列表失败')
      } finally {
        afterSaleLoading.value = false
      }
    }

    const getAfterSaleDetail = async (afterSaleId) => {
      try {
        const response = await axios.get(`${API_BASE_URL}/after-sales/${afterSaleId}`)
        if (response.data.success) {
          return response.data.data
        } else {
          ElMessage.error('获取售后详情失败')
          return null
        }
      } catch (error) {
        console.error('获取售后详情错误:', error)
        ElMessage.error('获取售后详情失败')
        return null
      }
    }

    const updateAfterSaleStatus = async (afterSaleId, status) => {
      try {
        const response = await axios.put(`${API_BASE_URL}/after-sales/${afterSaleId}/status`, { status })
        if (response.data.success) {
          return true
        } else {
          ElMessage.error(response.data.message || '更新状态失败')
          return false
        }
      } catch (error) {
        console.error('更新售后状态错误:', error)
        ElMessage.error('更新状态失败')
        return false
      }
    }

    // 商品管理相关方法
    const handleProductSearch = () => {
      productPagination.current = 1
      fetchProducts()
    }

    const resetProductSearch = () => {
      productSearchForm.productName = ''
      productSearchForm.username = ''
      productSearchForm.status = null
      productPagination.current = 1
      fetchProducts()
    }

    const handleProductPageChange = (page) => {
      productPagination.current = page
      fetchProducts()
    }

    const handleProductSizeChange = (size) => {
      productPagination.size = size
      productPagination.current = 1
      fetchProducts()
    }

    const getProductStatusText = (status) => {
      return productStatusMap[status]?.text || '未知状态'
    }

    const getProductStatusType = (status) => {
      return productStatusMap[status]?.type || 'info'
    }

    const getProductActionText = (status) => {
      return productStatusMap[status]?.action || '操作'
    }

    const handleToggleProductStatus = async (product) => {
      const currentStatus = product.status
      const nextStatus = productStatusMap[currentStatus]?.nextStatus
      const action = productStatusMap[currentStatus]?.action
      
      if (nextStatus === undefined) {
        ElMessage.error('无法确定下一步操作')
        return
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要${action}商品"${product.productName}"吗？`, 
          '提示', 
          { type: 'warning' }
        )
        await updateProductStatus(product.productId, nextStatus)
      } catch (error) {
        // 用户取消操作
      }
    }

    const handleDeleteProduct = async (product) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除商品"${product.productName}"吗？此操作不可恢复！`, 
          '警告', 
          { type: 'warning' }
        )
        await deleteProduct(product.productId)
      } catch (error) {
        // 用户取消操作
      }
    }

    // 订单管理相关方法
    const handleOrderSearch = () => {
      orderPagination.current = 1
      fetchOrders()
    }

    const resetOrderSearch = () => {
      orderSearchForm.orderId = ''
      orderSearchForm.buyerName = ''
      orderSearchForm.orderStatus = null
      orderPagination.current = 1
      fetchOrders()
    }

    const handleOrderPageChange = (page) => {
      orderPagination.current = page
      fetchOrders()
    }

    const handleOrderSizeChange = (size) => {
      orderPagination.size = size
      orderPagination.current = 1
      fetchOrders()
    }

    const getOrderStatusText = (status) => {
      return orderStatusMap[status]?.text || '未知状态'
    }

    const getOrderStatusType = (status) => {
      return orderStatusMap[status]?.type || 'info'
    }

    const handleViewOrderDetail = async (order) => {
      const orderDetail = await getOrderDetail(order.orderId)
      if (orderDetail) {
        currentOrder.value = orderDetail
        orderDetailVisible.value = true
      }
    }

    const handleCancelOrder = async (order) => {
      try {
        await ElMessageBox.confirm(
          `确定要取消订单"${order.orderId}"吗？如果订单已支付，将退款给买家。`, 
          '提示', 
          { type: 'warning' }
        )
        await cancelOrder(order.orderId)
      } catch (error) {
        // 用户取消操作
      }
    }

    const handleCompleteOrder = async (order) => {
      try {
        await ElMessageBox.confirm(
          `确定要完成订单"${order.orderId}"吗？系统将自动打款给卖家。`, 
          '提示', 
          { type: 'warning' }
        )
        await completeOrder(order.orderId)
      } catch (error) {
        // 用户取消操作
      }
    }

    // 用户管理相关方法
    const handleUserSearch = () => {
      userPagination.current = 1
      fetchUsers()
    }

    const resetUserSearch = () => {
      userSearchForm.username = ''
      userSearchForm.phone = ''
      userSearchForm.email = ''
      userPagination.current = 1
      fetchUsers()
    }

    const handleUserPageChange = (page) => {
      userPagination.current = page
      fetchUsers()
    }

    const handleUserSizeChange = (size) => {
      userPagination.size = size
      userPagination.current = 1
      fetchUsers()
    }

    const handleViewUserDetail = async (user) => {
      const userDetail = await getUserDetail(user.id)
      if (userDetail) {
        currentUser.value = userDetail
        userDetailVisible.value = true
      }
    }

    const handleEditUser = async (user) => {
      const userDetail = await getUserDetail(user.id)
      if (userDetail) {
        currentUser.value = userDetail
        // 填充编辑表单
        userEditForm.username = userDetail.username
        userEditForm.sign = userDetail.sign || ''
        userEditForm.avatar = userDetail.avatar || ''
        userEditForm.money = userDetail.money
        userEditVisible.value = true
      }
    }

    const handleSaveUser = async () => {
      if (!currentUser.value) return
      
      try {
        await ElMessageBox.confirm(
          `确定要更新用户"${currentUser.value.username}"的信息吗？`, 
          '提示', 
          { type: 'warning' }
        )
        
        const success = await updateUser(currentUser.value.id, userEditForm)
        if (success) {
          userEditVisible.value = false
        }
      } catch (error) {
        // 用户取消操作
      }
    }

    // 售后管理相关方法
    const handleAfterSaleSearch = () => {
      afterSalePagination.current = 1
      fetchAfterSales()
    }

    const resetAfterSaleSearch = () => {
      afterSaleSearchForm.orderId = ''
      afterSaleSearchForm.buyerName = ''
      afterSaleSearchForm.type = null
      afterSaleSearchForm.status = null
      afterSalePagination.current = 1
      fetchAfterSales()
    }

    const handleAfterSalePageChange = (page) => {
      afterSalePagination.current = page
      fetchAfterSales()
    }

    const handleAfterSaleSizeChange = (size) => {
      afterSalePagination.size = size
      afterSalePagination.current = 1
      fetchAfterSales()
    }

    const getAfterSaleTypeText = (type) => {
      return afterSaleTypeMap[type]?.text || '未知类型'
    }

    const getAfterSaleStatusText = (status) => {
      return afterSaleStatusMap[status]?.text || '未知状态'
    }

    const getAfterSaleStatusType = (status) => {
      return afterSaleStatusMap[status]?.type || 'info'
    }

    const handleViewAfterSaleDetail = async (afterSale) => {
      const afterSaleDetail = await getAfterSaleDetail(afterSale.afterSaleId)
      if (afterSaleDetail) {
        currentAfterSale.value = afterSaleDetail
        afterSaleDetailVisible.value = true
      }
    }

    const handleUpdateAfterSaleStatus = async (afterSale, newStatus) => {
      try {
        let confirmMessage = `确定要将售后申请状态修改为"${getAfterSaleStatusText(newStatus)}"吗？`
        if (newStatus === 5) {
          confirmMessage = '确定要确认完成此售后申请吗？确认后该记录将被删除！'
        }
        
        await ElMessageBox.confirm(confirmMessage, '提示', { type: 'warning' })
        
        const success = await updateAfterSaleStatus(afterSale.afterSaleId, newStatus)
        if (success) {
          if (newStatus === 5) {
            ElMessage.success('售后已完成，记录已删除')
            // 重新加载列表
            fetchAfterSales()
          } else {
            ElMessage.success('状态更新成功')
            // 更新本地数据状态
            afterSale.status = newStatus
            afterSale.processTime = new Date().toLocaleString()
          }
        } else {
          // 恢复原来的状态
          afterSale.status = afterSale.status
        }
      } catch (error) {
        // 用户取消操作，恢复原来的状态
        afterSale.status = afterSale.status
      }
    }

    // 选项卡切换处理
    const handleTabChange = (tabName) => {
      if (tabName === 'users' && userList.value.length === 0) {
        fetchUsers()
      } else if (tabName === 'afterSales' && afterSaleList.value.length === 0) {
        fetchAfterSales()
      }
    }

    // 初始化加载数据
    onMounted(() => {
      fetchProducts()
      // 默认加载第一页：订单数据
      fetchOrders()
    })

    return {
      activeTab,

      // 售后管理相关
      afterSaleLoading,
      afterSaleList,
      afterSaleSearchForm,
      afterSalePagination,
      afterSaleDetailVisible,
      currentAfterSale,
      
      // 售后管理方法
      handleAfterSaleSearch,
      resetAfterSaleSearch,
      handleAfterSalePageChange,
      handleAfterSaleSizeChange,
      getAfterSaleTypeText,
      getAfterSaleStatusText,
      getAfterSaleStatusType,
      handleViewAfterSaleDetail,
      handleUpdateAfterSaleStatus,
      handleTabChange,
      
      // 商品管理相关
      productLoading,
      productList,
      productSearchForm,
      productPagination,
      
      // 订单管理相关
      orderLoading,
      orderList,
      orderSearchForm,
      orderPagination,
      
      // 用户管理相关
      userLoading,
      userList,
      userSearchForm,
      userPagination,
      userDetailVisible,
      userEditVisible,
      currentUser,
      userEditForm,
      
      // 订单详情相关
      orderDetailVisible,
      currentOrder,
      
      // 商品管理方法
      handleProductSearch,
      resetProductSearch,
      handleProductPageChange,
      handleProductSizeChange,
      getProductStatusText,
      getProductStatusType,
      getProductActionText,
      handleToggleProductStatus,
      handleDeleteProduct,
      
      // 订单管理方法
      handleOrderSearch,
      resetOrderSearch,
      handleOrderPageChange,
      handleOrderSizeChange,
      getOrderStatusText,
      getOrderStatusType,
      handleViewOrderDetail,
      handleCancelOrder,
      handleCompleteOrder,
      
      // 用户管理方法
      handleUserSearch,
      resetUserSearch,
      handleUserPageChange,
      handleUserSizeChange,
      handleViewUserDetail,
      handleEditUser,
      handleSaveUser,
      handleTabChange
    }
  }
}
</script>

<style scoped>
.admin-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #000000;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-header p {
  margin: 5px 0 0;
  color: #707d98;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-tabs) {
  margin-top: 10px;
}

/* 用户头像样式 */
.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}
</style>